<?php

namespace handle\message\lib\manage;

use Exception;
use handle\message\lib\manage\lib\Player;
use handle\message\lib\traits\ManageObserver;

class PlayerManage
{
    use ManageObserver;

    /**
     * 创建玩家
     * @param string $room_id   房间ID
     * @param int $uid 玩家ID
     * @param string $name 玩家名称
     * @param int $homeowner 是否为房主
     * @return Player
     * @throws Exception
     */
    public function create(string $room_id, int $uid, string $name, int $homeowner): Player
    {
        if(!$this->checkPlayerIsset($room_id, $uid)){
            $this->observer[$room_id][$uid] = new Player($room_id, $uid, $name, $homeowner);
            $this->observer[$room_id][$uid]->setManage(self::$instance);
            $this->observer[$room_id][$uid]->init();
        }
        return $this->observer[$room_id][$uid];
    }

    /**
     * 检测玩家是否已存在
     * @param string $room_id
     * @param int $uid
     * @return bool
     * @throws Exception
     */
    public function checkPlayerIsset(string $room_id, int $uid): bool
    {
        return $this->isPlayerIsset($room_id, $uid);
    }

    /**
     * 设置玩家Socket连接器
     * @param string $room_id
     * @param int $uid
     * @param $connection
     * @return void
     * @throws Exception
     */
    public function setConnection(string $room_id, int $uid, $connection)
    {
        $this->getPlayer($room_id, $uid)->setConnection($connection);
    }

    /**
     * 更新玩家信息
     * @param string $room_id
     * @param int $uid 玩家ID
     * @param int $chess 棋子
     * @param int $mover 先后顺序
     * @return void
     * @throws Exception
     */
    public function updatePlayer(string $room_id, int $uid, int $chess = 0, int $mover = 0)
    {
        $this->getPlayer($room_id, $uid)->setPlayerInfo($chess, $mover);
    }

    /**
     * 检测是否有两个人
     * @param string $room_id
     * @return bool
     */
    public function isHasTwoPlayers(string $room_id): bool
    {
        return count($this->observer[$room_id]) == 2;
    }

    /**
     * 获取玩家回合
     * @param string $room_id
     * @param int $uid
     * @return bool
     * @throws Exception
     */
    public function isMyTurn(string $room_id, int $uid): bool
    {
        return $this->getPlayer($room_id, $uid)->isMyTurn();
    }

    /**
     * 获取对战玩家Player
     * @param string $room_id
     * @param int $uid 玩家ID
     * @return Player
     * @throws Exception
     */
    public function getOppositePlayer(string $room_id, int $uid): Player
    {
        if(count($this->observer[$room_id]) != 2) {
            throw new Exception(error('对战玩家数据异常994'));
        }
        $arr = $this->observer[$room_id];
        unset($arr[$uid]);
        return end($arr);
    }
}